Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};
// Require HTTP module (to start server) and Socket.IO
var http = require('http'),util = require('util');
var clients = new Array();
var commands = new Array();
var master = null;
// Start the server at port 8080
var server = http.createServer(function(req, res){ 

  // Send HTML headers and message
 res.writeHead(200,{ 'Content-Type': 'text/html' }); 
  res.end('<h1>Hello Socket Lover!</h1><Br>v0.01.2251');
});
server.listen(80);
// Create a Socket.IO instance, passing it our server
var io = require('socket.io').listen(server);
io.set("log level", 6);
/*interval = setInterval(function(){
console.log("Server is running");
console.log("Commands : ", commands);
}, 5000);*/


// Add a connect listener
io.sockets.on('connection', function(client){ 

	clients.push(client);
	io.sockets.emit("data", {noUsers : clients.length});
	
	// Success!  Now listen to messages to be received
	client.on('message',function(event){ 
		console.log('Received message from client!',event);
		io.sockets.send(event);
	});
	
	client.on('master', function(){ 
		master = client.id;
		
	});
	client.on('cmdChangeColor', function(color){
			io.sockets.json.emit('changeColor', {'color' : color});
			util.log('Color emitted');
			
		});
	client.on('cmdChangePart', function(part){
		io.sockets.json.emit('ChangePart', {'part' : part, 'cmdID' : 'cmid'});
	});
	
	client.on('disconnect',function(){
		i = clients.indexOf(client);
		s = clients.remove(i);
		client.emit("data", {noUsers : clients.length});
	});
});

function getID(length){
	sPassword = "";
    for (i=0; i < length; i++) {

        numI = getRandomNum();
        while (checkPunc(numI)) { numI = getRandomNum(); } 

        sPassword = sPassword + String.fromCharCode(numI);
	}

    return sPassword;
}

function getRandomNum() {

    // between 0 - 1
    var rndNum = Math.random()

    // rndNum from 0 - 1000
    rndNum = parseInt(rndNum * 1000);

    // rndNum from 33 - 127
    rndNum = (rndNum % 94) + 33;

    return rndNum;
}

function checkPunc(num) {

    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }

    return false;
}